package com.netease.web.system;

import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class FileUploadController {

	private final ResourceLoader resourceLoader;

	@Autowired
	public FileUploadController(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	// 显示图片的方法关键 匹配路径像
	// localhost:8080/pic/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png
	@RequestMapping(method = RequestMethod.GET, value = "/pic/{filename:.+}")
	@ResponseBody
	public ResponseEntity<?> getFile(@PathVariable String filename, HttpServletRequest request) {

		String path = request.getSession().getServletContext().getRealPath("/");
		path = path.substring(0, path.length() - 7);
		path = path + "resources\\static\\picture\\";
		try {
			path = Paths.get(path, filename).toString();
			Resource r = resourceLoader.getResource("file:" + path);
			return ResponseEntity.ok(r);
		} catch (Exception e) {
			return ResponseEntity.notFound().build();
		}
	}

}
